package org.fuxia.im.core.service.impl;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.server.ECSessionMananger;
import org.fuxia.im.core.socket.impl.ECNioServer;
import org.fuxia.im.core.utils.ObjectUtil;
import org.fuxia.im.db.dao.ChatGroupDaoImpl;
import org.fuxia.im.db.dao.UserChatGroupDaoImpl;
import org.fuxia.im.entities.ChatGroup;
import org.fuxia.im.entities.UserChatGroup;

import com.alibaba.fastjson.JSONArray;


public class AddChatGroupService extends AbstractService{

	@Resource
	private ChatGroupDaoImpl chatGroupDao ;
	
	@Resource
	private UserChatGroupDaoImpl ucgDao ;
	
	@SuppressWarnings("unchecked")
	public void service(ECPacket packet) {
		String gName = packet.getParameter("groupName") ;
		String owner = packet.getParameter("owner") ;
		String members = packet.getParameter("members") ;
		List<JSONArray> memberList = null;
		ChatGroup cg = new ChatGroup() ;
		cg.setOwnerId(owner);
		cg.setGroupName(gName);
		ECResponse resp = new ECResponse() ;
		resp.setResponseType("GROUP_ADD_RESULT");
		try {
			memberList  = ObjectUtil.getObjectByJson(members, List.class) ;
			String id = chatGroupDao.save(cg);
			List<UserChatGroup> ucg = new ArrayList<UserChatGroup>();
			for(int i=0;i<memberList.size();i++) {
				JSONArray temp = memberList.get(i);
				UserChatGroup ucgTemp= new UserChatGroup() ;
				ucgTemp.setChatGroupId(id);
				ucgTemp.setNickName(temp.getString(1)) ;
				ucgTemp.setUserCode(temp.getString(0)) ;
				ucg.add(ucgTemp);
				ucgDao.merge(ucgTemp);
			}
			ChatGroup cgNew = chatGroupDao.findByGroupId(id);
			resp.setStatusCode(200);
			resp.put("new_group", ObjectUtil.getJsonStr(cgNew)) ;
			resp.setResponseText("群组创建成功");
			
		} catch (Exception e) {
			e.printStackTrace();
			resp.setStatusCode(400);
			resp.setResponseText("群组创建失败") ;
		}
		try {
			writeReponse(packet, resp);
			resp.setResponseText("用户["+owner+"]将你加入到]"+gName+"]聊天群组中") ;
			notifyAllMembers(resp,memberList,owner);
		} catch (Exception e) {
			//no ops
		}
	}
	
	private void notifyAllMembers(ECResponse resp,List<JSONArray> meList,String owner) {
		if(meList!=null && meList.size()>0) {
			for(JSONArray array:meList) {
				String uCode = array.getString(0) ;
				if(uCode!=null&&!uCode.equals(owner) && ECSessionMananger.getInstance().hasLogin(uCode)) {
					try {
						ECNioServer.writeResponse(resp, ECSessionMananger.getInstance().getUserSession(uCode).getChannel()) ;
					} catch (Exception e) {
					}
				}
			}
		}
	}
}
